import React, { useState, useEffect } from 'react';
import { Card, Tag, Button, InputNumber, Select, Radio, Divider, message } from 'antd';
import { CheckCircleOutlined, SettingOutlined } from '@ant-design/icons';

interface ProductVariant {
  id: string;
  name: string;
  description?: string;
  basePrice: number;
  images: string[];
  specifications: Record<string, string>;
  parameters: VariantParameter[];
}

interface VariantParameter {
  id: string;
  name: string;
  type: 'select' | 'number' | 'radio';
  options?: { label: string; value: string; priceModifier?: number }[];
  min?: number;
  max?: number;
  unit?: string;
  required: boolean;
  description?: string;
  priceModifier?: number;
}

interface ProductVariantSelectorProps {
  variants: ProductVariant[];
  onVariantChange: (variant: ProductVariant, parameters: Record<string, any>, totalPrice: number) => void;
  onImageChange: (images: string[]) => void;
}

const ProductVariantSelector: React.FC<ProductVariantSelectorProps> = ({
  variants,
  onVariantChange,
  onImageChange
}) => {
  const [selectedVariant, setSelectedVariant] = useState<ProductVariant | null>(null);
  const [parameterValues, setParameterValues] = useState<Record<string, any>>({});
  const [totalPrice, setTotalPrice] = useState(0);

  // 初始化选择第一个变体
  useEffect(() => {
    if (variants.length > 0 && !selectedVariant) {
      const firstVariant = variants[0];
      setSelectedVariant(firstVariant);
      onImageChange(firstVariant.images);
    }
  }, [variants, selectedVariant, onImageChange]);

  // 计算总价格
  useEffect(() => {
    if (!selectedVariant) return;

    let price = selectedVariant.basePrice;
    
    // 根据参数值计算价格修正
    selectedVariant.parameters.forEach(param => {
      const value = parameterValues[param.id];
      if (value !== undefined) {
        if (param.type === 'select' || param.type === 'radio') {
          const option = param.options?.find(opt => opt.value === value);
          if (option?.priceModifier) {
            price += option.priceModifier;
          }
        } else if (param.type === 'number' && param.priceModifier) {
          price += (value || 0) * param.priceModifier;
        }
      }
    });

    setTotalPrice(price);
    onVariantChange(selectedVariant, parameterValues, price);
  }, [selectedVariant, parameterValues, onVariantChange]);

  const handleVariantSelect = (variant: ProductVariant) => {
    setSelectedVariant(variant);
    setParameterValues({}); // 重置参数值
    onImageChange(variant.images);
    message.success(`已选择工艺：${variant.name}`);
  };

  const handleParameterChange = (parameterId: string, value: any) => {
    setParameterValues(prev => ({
      ...prev,
      [parameterId]: value
    }));
  };

  const renderParameterInput = (parameter: VariantParameter) => {
    const value = parameterValues[parameter.id];

    switch (parameter.type) {
      case 'select':
        return (
          <Select
            value={value}
            onChange={(val) => handleParameterChange(parameter.id, val)}
            placeholder={`请选择${parameter.name}`}
            className="w-full"
            size="large"
          >
            {parameter.options?.map(option => (
              <Select.Option key={option.value} value={option.value}>
                <div className="flex justify-between items-center">
                  <span>{option.label}</span>
                  {option.priceModifier && (
                    <span className="text-blue-600 font-medium">
                      {option.priceModifier > 0 ? '+' : ''}¥{option.priceModifier}
                    </span>
                  )}
                </div>
              </Select.Option>
            ))}
          </Select>
        );

      case 'radio':
        return (
          <Radio.Group
            value={value}
            onChange={(e) => handleParameterChange(parameter.id, e.target.value)}
            className="w-full"
          >
            <div className="grid grid-cols-1 gap-2">
              {parameter.options?.map(option => (
                <Radio key={option.value} value={option.value} className="flex items-center">
                  <div className="flex justify-between items-center w-full">
                    <span>{option.label}</span>
                    {option.priceModifier && (
                      <span className="text-blue-600 font-medium ml-2">
                        {option.priceModifier > 0 ? '+' : ''}¥{option.priceModifier}
                      </span>
                    )}
                  </div>
                </Radio>
              ))}
            </div>
          </Radio.Group>
        );

      case 'number':
        return (
          <div className="flex items-center gap-2">
            <InputNumber
              value={value}
              onChange={(val) => handleParameterChange(parameter.id, val)}
              min={parameter.min}
              max={parameter.max}
              placeholder={`请输入${parameter.name}`}
              className="flex-1"
              size="large"
            />
            {parameter.unit && (
              <span className="text-gray-500">{parameter.unit}</span>
            )}
            {parameter.priceModifier && (
              <span className="text-blue-600 font-medium">
                ¥{parameter.priceModifier}/{parameter.unit || '单位'}
              </span>
            )}
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="space-y-6">
      {/* 工艺类型选择 */}
      <div>
        <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
          <SettingOutlined className="text-blue-600" />
          选择工艺类型
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {variants.map((variant) => (
            <Card
              key={variant.id}
              className={`cursor-pointer transition-all duration-300 hover:shadow-lg ${
                selectedVariant?.id === variant.id
                  ? 'border-blue-500 bg-gradient-to-br from-blue-50 to-indigo-50 shadow-lg'
                  : 'border-gray-200 hover:border-blue-300'
              }`}
              onClick={() => handleVariantSelect(variant)}
              styles={{ body: { padding: '16px' } }}
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <h4 className="font-bold text-gray-900">{variant.name}</h4>
                    {selectedVariant?.id === variant.id && (
                      <CheckCircleOutlined className="text-blue-500" />
                    )}
                  </div>
                  {variant.description && (
                    <p className="text-sm text-gray-600 mb-3">{variant.description}</p>
                  )}
                  <div className="flex items-center justify-between">
                    <span className="text-lg font-bold text-blue-600">
                      ¥{variant.basePrice}
                    </span>
                    <Tag color="blue">起</Tag>
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>

      {/* 参数配置 */}
      {selectedVariant && selectedVariant.parameters.length > 0 && (
        <div>
          <Divider />
          <h3 className="text-lg font-bold text-gray-900 mb-4 flex items-center gap-2">
            <span className="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center">
              <span className="text-white text-xs font-bold">⚙</span>
            </span>
            参数配置
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {selectedVariant.parameters.map((parameter) => (
              <div key={parameter.id} className="space-y-2">
                <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                  <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                  {parameter.name}
                  {parameter.required && <span className="text-red-500">*</span>}
                </label>
                {renderParameterInput(parameter)}
                {parameter.description && (
                  <p className="text-xs text-gray-500 bg-gray-50 p-2 rounded border-l-2 border-blue-300">
                    💡 {parameter.description}
                  </p>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 价格总计 */}
      {selectedVariant && (
        <div>
          <Divider />
          <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-6 border border-blue-200">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="text-lg font-bold text-gray-900">当前配置价格</h4>
                <p className="text-sm text-gray-600">工艺：{selectedVariant.name}</p>
              </div>
              <div className="text-right">
                <div className="text-3xl font-bold text-blue-600">¥{totalPrice}</div>
                <div className="text-sm text-gray-500">最终价格以实际报价为准</div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductVariantSelector;